package com.zwh.wx.controller;

import com.zwh.wx.handler.WxChatMsgFactory;
import com.zwh.wx.handler.WxChatMsgHandler;
import com.zwh.wx.utils.MessageUtil;
import com.zwh.wx.utils.SHA1;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@RestController
@Slf4j
public class CallBackController {

    // 微信回调验证所需的token
    private static final String token = "adwidhaidwoaidh";

    // 注入微信聊天消息工厂，用于处理不同类型的微信消息
    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    /**
     * 测试接口，返回一个简单的字符串
     *
     * @return 字符串 "hello world"
     */
    @RequestMapping("/test")
    public String test() {
        return "hello world";
    }

    /**
     * 微信回调验证端点
     * 用于验证微信服务器与开发者服务器的连通性
     *
     * @param signature 微信服务器发送的签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 用于验证的回响字符串
     * @return 如果签名验证通过，则返回 echostr，否则返回 "unknown"
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    /**
     * 微信消息回调端点
     * 接收微信服务器发送的消息，并根据消息类型和事件进行处理
     *
     * @param requestBody 请求体，包含微信消息的XML格式数据
     * @param signature 消息签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param msgSignature 消息体签名（可选）
     * @return 处理后的消息回复，以XML格式返回
     */
    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);
        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event") == null ? "" : messageMap.get("Event");
        log.info("msgType:{},event:{}", msgType, event);

        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WxChatMsgHandler wxChatMsgHandler = wxChatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(wxChatMsgHandler)) {
            return "unknown";
        }
        String replyContent = wxChatMsgHandler.dealMsg(messageMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }

}

